import { createSlice } from "@reduxjs/toolkit";
import { removeToken, request } from "@/utils";
import {setToken as _setToken,getToken}from '@/utils'
import { loginAPI,getUserInfoAPI } from "@/apis/user";
const userStore = createSlice({
  name: "user",
  initialState: {
    token: getToken() ||"",
    userInfo: {},
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      _setToken(action.payload);
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    clearUserInfo(state, action) {
      state.userInfo = {};
      state.token = "";
      removeToken();
    }
  },
});

//结构出来actionCreators喊出
const { setToken,setUserInfo,clearUserInfo } = userStore.actions;
//获取reducer函数
const userReducer = userStore.reducer;
//异步完成登录获取token

const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const res =await loginAPI(loginForm);
    dispatch(setToken(res.data.token));
  };
};
//获取个人用户信息
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res=await getUserInfoAPI()
    dispatch(setUserInfo(res.data));
  };
};
export { fetchLogin, setToken,fetchUserInfo,clearUserInfo };
export default userReducer;
